package cn.yx.common.mdc.thread;

import org.slf4j.MDC;

import java.util.Map;

/**
 * <p>MDC包装Runnable，线程中可支持MDC上下文信息</p>
 *
 * @author Wgssmart
 */
public class MdcRunnable implements Runnable {

    private final Runnable runnable;

    public MdcRunnable(Runnable runnable) {
        this.runnable = runnable;
    }

    @Override
    public void run() {
        Map<String, String> copyOfContextMap = MDC.getCopyOfContextMap();
        if (!copyOfContextMap.isEmpty()) {
            MDC.setContextMap(copyOfContextMap);
        }
        try {
            runnable.run();
        } finally {
            if (!copyOfContextMap.isEmpty()) {
                MDC.clear();
            }
        }
    }
}
